const poolPromise = require('../pools.js');
const { v4: uuidv4 } = require('uuid');
const getTime = require('../utils/getTime');
const { executeQuery } = require('../utils/dataAccess');

// 查询部门
exports.getDepartment = async (req, res, next) => {
    
    try {
        let sqlStatement = `SELECT 
            dept_id as deptId,
            dept_name as deptName,
            parent_id as parentId,
            order_num as orderNum,
            create_time as createTime
            FROM sys_dept where 1=1`;
        
        

        if(req.body.deptName){sqlStatement += ` and dept_name like '%${req.body.deptName}%'`;}

        // 添加order_num排序
        sqlStatement += ' order by order_num';


        const result = await executeQuery(sqlStatement);

        res.json({
            code: 200,
            message: '查询成功',
            data: result.rows
        });

    }
    catch (err) {
        next(err)
    }
}


exports.addDept = async (req, res, next) => {

    try {
        if(!req.body.deptName || !req.body.parentId || !req.body.orderNum){
            throw new Error('参数错误');
        }
    
        let sqlStatement = `INSERT INTO sys_dept ( dept_name, parent_id, order_num, create_time, create_by) VALUES ('${req.body.deptName}', '${req.body.parentId}', '${req.body.orderNum}', '${getTime()}', '${req.auth.user_name}')`;

        const result = await executeQuery(sqlStatement);

        res.json({
            code: 200,
            msg: '添加成功',
            data: result.rows
        })
    }
    catch (err) {
        next(err)
    }
}


exports.updateDept = async (req, res, next) => {
    try {
        if(!req.body.deptId || !req.body.deptName || !req.body.parentId || !req.body.orderNum) {
            throw new Error('参数错误');
        }
    
        let sqlStatement = `UPDATE sys_dept SET dept_name = '${req.body.deptName}', parent_id = '${req.body.parentId}', order_num = '${req.body.orderNum}', update_time = '${getTime()}', update_by = '${req.auth.user_name}' WHERE dept_id = '${req.body.deptId}'`;

        const result = await executeQuery(sqlStatement);

        res.json({
            code: 200,
            message: '更新成功',
            data: result.rows
        })
    }
    catch (err) {
        next(err)
    }
}


exports.deleteDept = async (req, res, next) => {
    try {
        if(!req.body.deptIds || req.body.deptIds.length == 0){
            throw new Error('参数错误');
        }
    
        let sqlStatement = `DELETE FROM sys_dept WHERE dept_id IN (${req.body.deptIds.map(item => `'${item}'`).join(',')})`;
        let sqlStatement2 = `DELETE FROM sys_role_dept WHERE dept_id IN (${req.body.deptIds.map(item => `'${item}'`).join(',')})`;
        let sqlStatement3 = `UPDATE sys_user SET dept_id = NULL WHERE dept_id IN (${req.body.deptIds.map(item => `'${item}'`).join(',')})`;

        const result = await executeQuery(sqlStatement + sqlStatement2 + sqlStatement3);

        res.json({
            code: 200, 
            msg: '删除成功', 
            data: result.rows
        });
    }
    catch (err) {
        next(err)
    }
}



async function menuFilter(id, data){
    let result = [];
    for(let i = 0; i < data.length; i++){
        if(data[i].parentId == id){
            result.push(data[i]);
            data[i].children = await menuFilter(data[i].deptId, data);
        }
    }
    return result;
}